import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
export default function ({ createApi, editApi, defaultForm, emit, props }) {
  const ruleFormRef = ref(null); // 表单ref
  const direction = ref("rtl"); // 抽屉的显示方向
  const loading = ref(false); // 按钮loading
  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit("update:modelValue", val),
  }); // 是否显示该抽屉

  const ruleForm = ref({
    ...defaultForm,
  }); // 表单内容
  const title = computed(() => {
    return props.type === "update" ? "编辑" : "新增";
  });

  // 关闭窗口
  const beforeClose = () => {
    visible.value = false;
    ruleFormRef.value && ruleFormRef.value.clearValidate();
  };
  // 新增
  const createFn = async () => {
    const res = await createApi(ruleForm.value);
    if (res.status === 200 || res.status === 201) {
      ElMessage.success("新增成功");
      emit("update-list");
      beforeClose();
      loading.value = false;
    }
  };
  // 修改
  const editFn = async () => {
    const res = await editApi(ruleForm.value);
    ElMessage.success("修改成功");
    if (res.status === 200 || res.status === 201) {
      emit("update-list");
      beforeClose();
      loading.value = false;
    }
  };

  // 提交
  const submit = () => {
    loading.value = true;
    ruleFormRef.value.validate((valid) => {
      if (valid) {
        props.type === "create"
          ? createFn().catch(() => {
              loading.value = false;
            })
          : editFn().catch(() => {
              loading.value = false;
            });
      } else {
        ElMessage.warning("请仔细检查是否有必填字段没有填写！");
        loading.value = false;
        return false;
      }
    });
  };
  return {
    direction,
    visible,
    loading,
    title,
    ruleForm,
    ruleFormRef,
    beforeClose,
    submit,
  };
}
